package com.lmh.backend.dao.daoImpl;

import com.lmh.backend.dao.UserDao;
import com.lmh.backend.entity.User;
import com.lmh.backend.utils.JpaUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public User getUserByName(String username) {
        EntityManager manager = JpaUtils.getEntityManager();
        Query query = manager.createQuery("select u from User u where u.username = ?");
        query.setParameter(1, username);
        List<User> resultList = query.getResultList();
        return resultList.isEmpty()?null:resultList.get(0);
    }

    @Override
    public void save(User user) {
        EntityManager manager = JpaUtils.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        manager.persist(user);
        transaction.commit();
    }
}
